<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Shop\Cart;
use JWTAuth;

class CartController extends Controller
{
    /***
     * 购物车列表
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        $user = JWTAuth::parseToken()->authenticate();

        $carts = Cart::with('good')->where('customer_id', $user->id)->get();
        $count = Cart::count_cart($carts);
        return compact('carts', 'count');
    }


    /***
     * 将商品加入购物车
     * @param Request $request
     */
    public function store(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();

        //接收商品的id
        $good_id = $request->good_id;
        $cart = Cart::where('good_id', $good_id)->where('customer_id', $user->id)->first();

        //判断购物车是否有此商品，如果有，那么 数量+1
        if ($cart) {
            Cart::where('id', $cart->id)->increment('num');
            return;
        }

        //否则购物车表，创建新数据
        Cart::create([
            'good_id' => $request->good_id,
            'customer_id' => $user->id
        ]);
    }

    /***
     * 改变数量
     * @param Request $request
     * @return array
     */
    public function change_num(Request $request)
    {
        if ($request->type == 'add') {
            Cart::where('id', $request->id)->increment('num');
        } else {
            Cart::where('id', $request->id)->decrement('num');
        }
        return Cart::count_cart();
    }

    /***
     * ajax删除商品
     * @param Request $request
     * @return array
     */
    public function destroy(Request $request)
    {
        Cart::destroy($request->id);
        return Cart::count_cart();
    }
}
